use strict;
use warnings;
use Image::Magick;
use Data::Dumper;

system("dot -Tpng <techtree.dot >techtree.png") and die "couldn't generate .png of techtree";
system("dot -Tplain <techtree.dot >techtree.txt") and die "couldn't generate .txt of techtree";

my $temp = new Image::Magick->new();
$temp->ReadImage('techtree.png');
my $w = $temp->Get('width');
my $h = $temp->Get('height');
my $origw = $w;
my $origh = $h;
my $scalefactorX = 512/$w;
my $scalefactorY = 256/$h;
$w = 512;
$h = 256;
$temp->Resize(width=>$w, height=>$h);
open OUT, ">..\\data\\techtree.bin" or die "couldn't open ..\\data\\techtree.bin for output";
binmode(OUT);
for (my $y = 0; $y < $h; $y++)
{
	for (my $x = 0; $x < $w; $x++)
	{
		my @rgb = $temp->GetPixels(width => 1, height => 1, x => $x, y => $y, normalize => 'true');
		die "non-greyscale" if $rgb[0] ne $rgb[1];
		die "non-greyscale" if $rgb[0] ne $rgb[2];
		my $v = 1 - $rgb[0];
		print OUT pack('C', (31 * $v));
	}
}
close OUT;
$temp->Write('techtree_sized.png');

my %Dependents;
open IN, "techtree.dot" or die "couldn't open techtree.dot";
while (<IN>)
{
	chomp;
	if (m/\t(.*)/) # blech, ignore all lines that don't start with a tab
	{
		my $line = $1;
		my @parts = split / -> /, $line;
		push @{$Dependents{$parts[0]}}, $parts[1];
	}
}
close IN;
sub getDependents($)
{
	my $for = shift;
	my $ret = '';
	my $count = 0;
	foreach my $dep (@{$Dependents{$for}})
	{
		$ret .= 'Tech_' . $dep . ", ";
		$count++;
	}
	for (; $count < 4; ++$count)
	{
		$ret .= 'Tech_Invalid, ';
	}
	return $ret;
}


open IN, "techtree.txt" or die "couldn't open techtree.txt";
my $graph = <IN>;
my @firstLine = split /\s+/, $graph;
my $origWInches = $firstLine[2];
my $origHInches = $firstLine[3];

my $inchesToPixelsX = ($origw / $origWInches) * $scalefactorX;
my $inchesToPixelsY = ($origh / $origHInches) * $scalefactorY;

my $header = "#ifndef LG_INCLUDED_techtree_H\n#define LG_INCLUDED_techtree_H\n\n// THIS FILE IS GENERATED BY BUILDTT.PL\n\n#include <nds/jtypes.h>\n\nenum Technology\n{\n\tTech_Invalid = -1,\n";
my $cfile = "// THIS FILE IS GENERATED BY BUILDTT.PL\n\n#include \"techtree.h\"\n\nconst TechnologyInfo gTechInfo[] =\n{\n";

my %CostOf = (
	Farming => 1250,
	Wheel => 300,
	Animal__Husbandry => 300,
	Agriculture => 250,
	Masonry => 350,
	Mining => 200,
	Metal_Work => 200,
	Irrigation => 350,
	Machinery => 800,
	Fossil_Fuels => 1100,
	Compass => 450,
	Mathematics => 2000,
	Alphabet => 800,
	Maps => 1000,
	War_Boats => 2250,
	Construction => 1250,
	Engineering => 6000,
	Currency => 3000,
	Trade_Routes => 4500,
	Education => 9000,
	Fusion => 35000,
	Medicine => 20000,
	Advanced_Construction => 15000,
	Tornado__Resistance => 9000,
	Religion => 35000,
);

my %ResultOf = (
	Farming => "You can now build Farms",
	Wheel => "You are now more productive",
	Animal__Husbandry => "Bonus production from Crops",
	Agriculture => "Crops supply more food per acre",
	Masonry => "Huts support more people",
	Mining => "Faster building of Huts and Crops",
	Metal_Work => "Defense bonus against attacks",
	Irrigation => "Hardy Crops, Bonus food from Farms",
	Machinery => "Building now proceeds faster",
	Fossil_Fuels => "Can build Factories; beware pollution",
	Compass => "You can now attack the other island",
	Mathematics => "Research now proceeds faster",
	Alphabet => "You can now build Schools",
	Maps => "You can now see the whole map",
	War_Boats => "Double destruction when attacking",
	Construction => "You can now build Houses",
	Engineering => "You can now reclaim land",
	Currency => "You are now more productive",
	Trade_Routes => "You can now import food",
	Education => "You can now build a University",
	Fusion => "You now now launch Missiles to 'win'.",
	Medicine => "You can now build a Hospital",
	Advanced_Construction => "You can now build Apartments",
	Tornado__Resistance => "Buildings are tornado resistant",
	Religion => "Much higher birthrate"
);

while (1)
{
	my @line = split(/\s+/, <IN>);
	last if ($line[0] ne 'node');
	my $newX = int($line[2] * $inchesToPixelsX);
	my $newY = int($h - ($line[3] * $inchesToPixelsY));
	my $boxW = int($line[4] * $inchesToPixelsX);
	my $boxH = int($line[5] * $inchesToPixelsY);
	my $text = $line[1];
	$text =~ s/_/ /g;
	$text =~ s/Advanced/Adv./g;
	$text =~ s/  / /g;
	$header .= "\tTech_$line[1],\n";
	my $dependents = getDependents($line[1]);
	if ($line[1] eq 'Construction' || $line[1] eq 'Irrigation')
	{
		$newX++;
	}
	$cfile .= "\t{ \"$text\", \"$ResultOf{$line[1]}\", $CostOf{$line[1]}, $newX, $newY, $boxW, $boxH, { $dependents} },\n";
}

close IN;

$header .= "\tTech_Count\n};\n\nstruct TechnologyInfo\n{\n\tconst char* name;\n\tconst char* result;\n\tu16 cost;\n\tu16 screenX, screenY;\n\tu16 width, height;\n\tTechnology dependents[4];\n};\n\nextern const TechnologyInfo gTechInfo[];\n\n#define LG_TECHTREE_BITMAP_WIDTH ${w}\n#define LG_TECHTREE_BITMAP_HEIGHT ${h}\n\n#endif\n";
$cfile .= "};\n\n";

open OUT, ">arm9/source/techtree.h" or die "couldn't open arm9/source/techtree.h for output\n";
print OUT $header;
close OUT;
open OUT, ">arm9/source/techtree.cpp" or die "couldn't open arm9/source/techtree.cpp for output\n";
print OUT $cfile;
close OUT;
